package org.niugang.coding.conf;


import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 全局缓存(基于内存的)
 *
 * @author Created by niugang on 2019/1/23/21:29
 */
public class CacheMap {

    private static int DEFAULT_CACHE_MINUTE = 1;
    /**
     * 数据缓存map
     */
    private static Map<String, Object> dataMap = new ConcurrentHashMap<>();
    /**
     * 数据缓存过期map
     */
    private static Map<String, Date> dataExpireMap = new ConcurrentHashMap<>();

    /**
     * 将一个key、value值放入内存缓存
     *
     * @param key 键
     * @param val 值
     */
    public synchronized static void put(String key, Object val) {
        put(key, val, DEFAULT_CACHE_MINUTE);
    }

    /**
     * 将一个key、value值放入内存缓存,并设置过期分钟数
     *
     * @param key         键
     * @param val         值
     * @param expireMiute 过期时间(分钟)
     */
    public synchronized static void put(String key, Object val, int expireMiute) {
        if (expireMiute <= 0) {
            throw new IllegalArgumentException("expireMiute");
        }
        dataMap.put(key, val);
        Calendar instance = Calendar.getInstance();
        instance.add(Calendar.MINUTE, DEFAULT_CACHE_MINUTE);
        Date time = instance.getTime();
        dataExpireMap.put(key, time);
    }

    /**
     * 从缓存中获取一个key的数据(若过期返回null)
     *
     * @param cacheKey 键
     * @return Object
     */
    public synchronized static Object get(String cacheKey) {
        Object obj = null;
        Date expireDate = CacheMap.dataExpireMap.get(cacheKey);
        if (expireDate != null && expireDate.compareTo(new Date()) > 0) {
            obj = CacheMap.dataMap.get(cacheKey);
        } else {
            if (CacheMap.dataMap.containsKey(cacheKey)) {
                CacheMap.dataMap.remove(cacheKey);
            }
            if (CacheMap.dataExpireMap.containsKey(cacheKey)) {
                CacheMap.dataExpireMap.remove(cacheKey);
            }

        }
        return obj;
    }

    /**
     * 判断是否包含某个键
     *
     * @param cacheKey 键值
     * @return boolean
     */
    public synchronized static boolean containsKey(String cacheKey) {
        return CacheMap.dataMap.containsKey(cacheKey);
    }

    /**
     * 移除键值
     *
     * @param cacheKey 键值
     */
    public synchronized static void remove(String cacheKey) {
        CacheMap.dataMap.remove(cacheKey);
    }
}
